package com.example.jetpackstu.ui.news

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.example.jetpackstu.logic.Repository

class DetailViewModel : ViewModel() {

    private val newsId = MutableLiveData<Long>()

    val title = MutableLiveData("")

    val content = MutableLiveData("")

    val news = Transformations.switchMap(newsId) { id ->
        Repository.newsById(id)
    }

    fun getNews(id: Long) {
        newsId.value = id
    }

    fun save() {
        if (news.value == null) {
            // 保存
            Repository.newsSave(title.value!!, content.value!!)
        } else {
            // 更新
            Repository.newsUpdate(news.value!!)
        }
    }
}